package game.view {

	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	
	import flashx.textLayout.formats.Float;
	
	import game.ui.SceneUI;
	
	import morn.core.components.Image;
	import morn.core.components.Label;
	import morn.core.components.LinkButton;
	
	import tools.gameSound.GameSound;
	import tools.tweenLiteTool.TweenLite;
	import tools.tweenLiteTool.easing.Linear;


	public final class GameStage extends SceneUI {
		
		private var richGoldStatus:Boolean = false;
		private var nowDirection:int;
		private var timeHandle:Date;
		private var nowTime:int;
		private var dropTime:int = 0;
		private var num:int = 0;
		private var rateData:Array;
		private var imgData:Array;
		private var itemData:Object = {};
		private var itemScoreData:Array;
		private var limitTime:int = 10;
		private var startBtn:LinkButton;
		private var overBtn:LinkButton;
		private var moreGameBtn:LinkButton;
		private var setTime:int = 0;
		private var restTime:int = 0;
		private var scoreMix:int = 1000;
		private var level:int = 0;
		private var nowScore:int;
		private var mySound:GameSound;
		private var godLeftX:int = 270;
		private var godRightX:int = 600;
		
		private const defaultW:Number = 840;
		private const defaultH:Number = 620;

		private const midScale:Number = 0.5;
		private var SCALERATE:Number = defaultW / defaultH;
		
		private var open3366Service:*;                 // 3366
		private var serviceHold:*;                     // 4399
		
		public function GameStage() {
			mySound = new GameSound();
			rateData      = [0.6, 0.5, 0.3, 0.2, 0.8];
			imgData       = ["dropGood03", "dropGood02", "dropGood01", "dropGood04", "dropGood05"];
			itemScoreData = [10, 20, 50, 80, -10];
		}
		
		public function init():void {
			App.stage.addEventListener(Event.ENTER_FRAME, enterFrame);
			App.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);				 //添加键盘按键按下事件
			App.stage.addEventListener(KeyboardEvent.KEY_UP, keyUp);					 //添加键盘按键松开事件
			
			setStartBtn();
			music();
			
			this.smallPlayer.autoPlay = true;
		}
		
		public function set3366Service(service:*):void {
			open3366Service = service;
		}
		
		public function set4399Service(hold:*):void {
			serviceHold = hold;
		}
		
		private function setStartBtn():void {
			startBtn             = new LinkButton;
			startBtn.label       = "点击开始";
			startBtn.labelSize   = 30;
			startBtn.labelColors = "0x00FF00";
			startBtn.x           = (this.sceneView.width - 120) * .5;
			startBtn.y           = (this.sceneView.height - 30) * .5;
			startBtn.labelBold   = true;
			startBtn.buttonMode  = true;
			startBtn.labelStroke = "0x000000";
			this.sceneView.addChild(startBtn);
			startBtn.addEventListener(MouseEvent.CLICK, startGame);
		}
		
		private function startGame(e:MouseEvent):void {
			startBtn.visible = false;
			if(overBtn != null) {
				overBtn.visible = false;
			}
			if(moreGameBtn != null) {
				moreGameBtn.visible = false;
			}
			//restTime = limitTime;
			
			
			clearScore();
			richGoldStart();
		}
		
		private function richGoldStart():void {
			if(richGoldStatus) {
				return;
			}
			this.richGod.x = godLeftX;
			richGoldStatus = true;
			richGodMove(1);
		}

		private function richGodMove(_direction:int):void {
			
			var direction:int = (_direction == 0) ? 1 : 0;
			var sizeX:int = (_direction == 0) ? godLeftX : godRightX;
			TweenLite.to(this.richGod, 3, {x:sizeX, ease:Linear.easeNone, onComplete:richGodMove, onCompleteParams:[direction]});
		}
		
		private function richGodMoveClear():void {
			TweenLite.killTweensOf(this.richGod, true);
		}
		
		private function smallPalyerMove(_direction:int):void {
			if(!richGoldStatus) {
				return;
			}
			
			if(_direction != nowDirection) {
				nowDirection = 	_direction;
				smallPalyerMoveClear();
				var time:Number  = 0;    // 秒
				var leftX:int    = 300;
				var rightX:int   = 780;
				var speed:Number = 150;  // 像素/每秒
				if(_direction == 0) {
					//if(treasureXMLHandle.smallPlayer.x == sizeX) {
					
					//bground.skin = "assets.frameclip_bg";
					//bground.alpha = 0;
					//bground.autoPlay = true;
					this.smallPlayer.skin     = "assets.frameclip_rightP";
					this.smallPlayer.autoPlay = true;
					time = (this.smallPlayer.x - leftX) / speed;
					TweenLite.to(this.smallPlayer, time, {x: leftX, ease:Linear.easeNone});
					//}
				}
				else if(_direction == 1) {
					//if(treasureXMLHandle.smallPlayer.x == 0) {
					this.smallPlayer.skin     = "assets.frameclip_leftP";
					this.smallPlayer.autoPlay = true;
					time = (rightX - this.smallPlayer.x) / speed;
					//treasureXMLHandle.smallPlayer.source = xiaoguai_right;
					TweenLite.to(this.smallPlayer, time, {x: rightX, ease:Linear.easeNone});
					//}
				}
			}
		}
		
		private function smallPalyerMoveClear():void {
			TweenLite.killTweensOf(this.smallPlayer);
			nowDirection = -1;
		}
		
		private function itemSpeed():int {
			var randnum:int = Math.round( Math.random() * 99);
			if(randnum < 50) {
				randnum = Math.round( Math.random() * (200 - 100) ) + 100;
			}
			else {
				randnum = Math.round( Math.random() * (50 - 20) ) + 30;
			}
			return randnum;
		}
		
		private function getGapTime():int {
			//var gapTime:int = Math.round( Math.random() * 10 ) + 2;
			//gapTime = 90 * gapTime;
			var gapTime:int = 50
			return gapTime;
		}
		
		private function dropOut():void {
			if(!richGoldStatus) {
				return;
			}
			
			if(dropTime == 0) {
				dropTime = nowTime;
			}
			
			
			if(nowTime - dropTime > getGapTime()) {
				
				var randV:int = Math.round( Math.random() * 99 );
				if(randV > 5) {
					return;
				}
				
				dropTime = nowTime;
				num      = num % 5;

				var randnum:int = Math.round( Math.random() * 99 );
				var kind:int = 0;
				if(randnum < 50) {
					kind = 4;
				}
				else {
					kind = num;
					//trace(kind,num);
				}
				
				addItem(kind);
				
				num++;
			}
		}
		
		private function addItem(_kind:int, _newX:int = -1):void {
			var randomValue:Number = Math.random();
			var randnum:int = Math.round( randomValue * 99 );
			var key:int = nowTime + randomValue * 100000;
			var time:Number = 550 / itemSpeed();

			var newX:int;
			
			var itemImg:Image = new Image();
			itemImg.url   = "png.other." + imgData[_kind];
			itemImg.y     = 150;
			itemImg.kind  = _kind;
			itemData[key] = itemImg;

			if(_newX != -1) {
				_newX = _newX >= godLeftX ? _newX : godLeftX;
				newX  = _newX;
			}
			else {
				var dis:int = randnum > 49 ? 176 : 0;
				newX = this.richGod.x + dis
			}

			itemImg.x = newX;
			this.sceneView.addChild(itemData[key]);
			TweenLite.to(itemData[key], time, {y:700, ease:Linear.easeNone, onComplete:dropOutClear, onCompleteParams:[key]});
			itemImg = null;
			
			if(_kind == 2 || _kind == 3) {
				addItem(4, this.richGod.x - 40);
			}
		}
		
		private function dropOutClear(_key:int):void {
			if(itemData[_key] != null) {
				this.sceneView.removeChild(itemData[_key]);
				itemData[_key] = null;
			}
		}
		
		/*private function setRestTime():void {
			if(!richGoldStatus) {
				return;
			}
			
			if(setTime == 0) {
				setTime = nowTime;
			}
			
			if(nowTime - setTime >= 1000) {
				setTime = nowTime;
				restTime--;
				restTime = restTime > 0 ? restTime : 0;
				this.leftTime.text = String(restTime);
				if(restTime == 0) {
					richGoldStatus = false;
					// game end
				}
			}
		}*/
		
		private function checkHit():void {
			if(!richGoldStatus) {
				return;
			}
			
			var itemPos:Point, tPos:Point;
			//tPos = new Point(treasureXMLHandle.smallPlayer.x + 60, treasureXMLHandle.smallPlayer.y + 80);
			tPos = new Point(this.smallPlayer.x, this.smallPlayer.y);
			var kind:int = 0;
			var gap:int  = 30;
			for(var i:* in itemData) {
				if(itemData[i] != null && itemData[i].visible) {
					kind = itemData[i].kind;
					itemPos = new Point(itemData[i]["x"] + 25, itemData[i]["y"] + 25);
					//gap = (kind == 4) ? 100 : 25
					if(Point.distance(tPos, itemPos) < gap) {
						hit(i);
					}
				}
				
				if(itemData[i] != null) {
					/*var randnum:int = Math.round( Math.random() * 99);
					if(randnum < 50) {
						if(itemData[i].y == 460) {
							TweenLite.to(itemData[i], 2, {alpha: 0.5,y : 800, onComplete:dropOutClear, onCompleteParams:[i]});
						}
					}*/
				}
			}
		}
		
		private function clearScore():void {
			nowScore = 0;
			this.totalScore.text = String(nowScore);
		}
		
		private function hit(_key:int):void {
			if(itemData[_key] != null) {
				itemData[_key].visible = false;
				var kind:int = itemData[_key].kind;
				if(kind == 4) {
					boneSound();
					richGoldStatus = false;
					clear();
					over();
				}
				else {
					hitSound();
					nowScore += itemScoreData[kind];
					this.totalScore.text = String(nowScore);
				}
				
				/*switch(kind) {
					case 0:
						//this.tcLabel.text = int(this.tcLabel.text) + itemScoreData[kind];
						//this.tcLabel.text = String(int(this.tcLabel.text) + 1);
						break;
					case 1:
						//this.yyLabel.text = int(this.yyLabel.text) + itemScoreData[kind];
						//this.yyLabel.text = String(int(this.yyLabel.text) + 1);
						break;
					case 2:
						//this.ybLabel.text = int(this.ybLabel.text) + itemScoreData[kind];
						//this.ybLabel.text = String(int(this.ybLabel.text) + 1);
						break;
					case 3:
						//this.zsLabel.text = int(this.zsLabel.text) + itemScoreData[kind];
						//this.zsLabel.text = String(int(this.zsLabel.text) + 1);
						break;
					case 4:
						// 炸弹爆炸
						break;
				}*/
				
			}
		}
		
		private function over():void {
			
			confirmScore();
			
			showAgainBtn();
			
			showMoreGameBtn();
		}
		
		private function showAgainBtn():void {
			if(overBtn == null) {
				overBtn             = new LinkButton;
				overBtn.label       = "再来一次";
				overBtn.labelSize   = 30;
				overBtn.labelColors = "0x00FF00";
				overBtn.x           = (this.sceneView.width - 130) * .5;
				overBtn.y           = (this.sceneView.height - 30) * .5;
				overBtn.labelBold   = true;
				overBtn.buttonMode  = true;
				overBtn.labelStroke = "0x000000";
				this.sceneView.addChild(overBtn);
				overBtn.addEventListener(MouseEvent.CLICK, startGame);
			}
			overBtn.visible = true;
		}
		
		private function showMoreGameBtn():void {
			var show:Boolean = false;
			
			if(serviceHold != null) {
				show = true;
			}
			
			if(open3366Service != null) {
				show = true;
			}
			
			if(show == false) {
				return;
			}
			
			if(moreGameBtn == null) {
				moreGameBtn             = new LinkButton;
				moreGameBtn.label       = "更多游戏";
				moreGameBtn.labelSize   = 30;
				moreGameBtn.labelColors = "0x00FF00";
				moreGameBtn.x           = (this.sceneView.width - 130) * .5;
				moreGameBtn.y           = (this.sceneView.height - 30) * .5 + 40;
				moreGameBtn.labelBold   = true;
				moreGameBtn.buttonMode  = true;
				moreGameBtn.labelStroke = "0x000000";
				this.sceneView.addChild(moreGameBtn);
				moreGameBtn.addEventListener(MouseEvent.CLICK, moreGame);
			}
			moreGameBtn.visible = true;
		}
		
		private function moreGame(e:MouseEvent):void {
			if(serviceHold != null) {
				serviceHold.showGameList();
			}
			if(open3366Service != null) {
				open3366Service.recomGame(); 
			}
		}
		
		private function confirmScore():void {
			if(open3366Service != null) {
				open3366Service.submitScore(nowScore);
			}
			else if(serviceHold != null) {
				serviceHold.showRefer(nowScore)
			}
		}
		
		private function hitSound():void {
			mySound.soundPlay("resources/sound/sound01.mp3");
		}
		
		private function boneSound():void {
			mySound.soundPlay("resources/sound/sound02.mp3");
		}
		
		private function music():void {
			mySound.musicPlay("resources/sound/music01.mp3", 0, 999);
		}
		
		private function clear():void {
			for(var i:* in itemData) {
				if(itemData[i] != null) {
					TweenLite.killTweensOf(itemData[i], true);
					dropOutClear(i);
				}
			}
			
			richGodMoveClear();
			
			smallPalyerMoveClear();
		}
		
		public function keyDown(e:KeyboardEvent):void {
			switch(e.keyCode) {
				case 65:
				case 37:
					// 左
					smallPalyerMove(0);
					break;
				case 68:
				case 39:
					// 右
					smallPalyerMove(1);
					break;
			}
		}
		
		private function keyUp(e:KeyboardEvent):void {
		
		}
		
		private function setNowTime():void {
			timeHandle = new Date();
			nowTime    = timeHandle.time;
		}
		
		private function enterFrame(e:Event):void {
			setNowTime();
			
			//setRestTime();
			
			checkHit();
			
			dropOut();
		}
		
		public function sizeAuto():void {
			var stageW:int = this.stage.stageWidth;
			var stageH:int = this.stage.stageHeight;
			var stageScaleRate:Number = stageW / stageH;
			
			if(stageScaleRate >= SCALERATE) {
				// 超过1240:800则以高为基准
				if(stageH / defaultH > midScale) {
					this.sceneView.scale = stageH / defaultH;
				}
				else {
					this.sceneView.scale = midScale;
				}
			}
			else if(stageScaleRate < SCALERATE) {
				// 小于1240:800则以宽为基准
				if(stageW / defaultW > midScale) {
					this.sceneView.scale = stageW / defaultW;
				}
				else {
					this.sceneView.scale = midScale;
				}
			}
			this.sceneView.scale = (this.sceneView.scale >= 1) ? 1 : this.sceneView.scale;
			this.sceneView.x = (this.stage.stageWidth - defaultW * this.sceneView.scale)*.5;
			this.sceneView.y = (this.stage.stageHeight - defaultH * this.sceneView.scale)*.5;
		}
		
		public function sizeAuto2():void {
			var stageW:int = this.stage.stageWidth;
			var stageH:int = this.stage.stageHeight;

			this.sceneView.scaleX = stageW / defaultW;
			this.sceneView.scaleY = stageH / defaultH;
		}
		
		public function sizeAuto3():void {
			var stageW:int = this.stage.stageWidth;
			var stageH:int = this.stage.stageHeight;
			
			this.sceneView.scaleX = stageW / defaultW;
			this.sceneView.scaleY = stageH /defaultH;
		}

	}
}